<template>
  <div class="choose-organization-container" id="choose-organization-container">
    <a-popover
      trigger="click"
      :getPopupContainer="getContainer"
      overlayClassName="choose-organization-popover"
      :destroyTooltipOnHide="true"
      v-model="visible"
      @visibleChange="visibleChange($event)"
    >
      <div class="popover-target-container">
        <div class="name">{{ currenData.tenantName }}</div>
        <a-icon type="down" :class="visible && 'rotate'" />
      </div>
      <!-- popover内容区域 -->
      <div slot="content" class="popover-drow-container">
        <div class="popover-drow-header">
          <div class="tenant-name">{{ currentTenant.tenantName }}</div>
          <div class="check-button-warp">
            <a-tooltip placement="top">
              <template slot="title"> 组织视图 </template>
              <div
                class="check-button"
                :class="organizationType == 0 && 'active'"
                @click="checkOrganizationType(0)"
              >
                <bj-icon-font
                  type="tree_line"
                  :color="organizationType == 0 ? '#fff' : '#8a8a8c'"
                  :size="15"
                />
              </div>
            </a-tooltip>
            <a-tooltip placement="top">
              <template slot="title"> 项目视图 </template>
              <div
                class="check-button"
                :class="organizationType == 1 && 'active'"
                @click="checkOrganizationType(1)"
              >
                <bj-icon-font
                  type="project_space"
                  :color="organizationType == 1 ? '#fff' : '#8a8a8c'"
                  :size="15"
                />
              </div>
            </a-tooltip>
            <a-tooltip placement="top">
              <template slot="title"> 切换租户 </template>
              <div class="check-button" @click="openChooseTenant()">
                <bj-icon-font type="qiehuan" color="#8a8a8c" :size="15" />
              </div>
            </a-tooltip>
          </div>
        </div>
        <div class="popover-drow-body">
          <!-- 组织结构树 -->
          <div
            class="carousel-item-container custom-scrollbar"
            v-if="organizationType == 0"
          >
            <a-tree
              :tree-data="orgSource"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              show-icon
              blockNode
              :replaceFields="{
                children: 'child',
                title: 'tenantName',
                key: 'tenantCode',
              }"
              @expand="onExpand"
              @select="selectOrganization"
            >
              <bj-icon-font slot="group" type="tree_line" :size="15" />
              <template
                slot="custom"
                slot-scope="{ child, expanded, selected }"
              >
                <!-- expanded 展开  children 是否包含子节点 -->
                <a-icon
                  :type="expanded ? 'folder-open' : 'folder'"
                  v-if="child"
                />
                <bj-icon-font
                  type="project_space"
                  :size="15"
                  :color="selected ? '#fff' : '#8a8a8c'"
                  v-else
                />
              </template>
            </a-tree>
          </div>

          <!-- 项目列表 -->
          <div class="carousel-item-container custom-scrollbar" v-else>
            <div
              class="pro-list-warp"
              :class="organization.proCode == item.proCode && 'active'"
              v-for="item in projectData"
              :key="item.id"
              @click="selectProject(item)"
            >
              {{ item.proName }}
            </div>
          </div>
        </div>
      </div>
    </a-popover>
  </div>
</template>

<script>
import _ from "lodash";
import { mapGetters } from "vuex";
import { addAttributeByKey, flatTreeData } from "@/utils";
import { saveData, getMenuData } from "@/tools";
export default {
  name: "ChooseOrganization",
  data() {
    return {
      //是否可见
      visible: false,
      //视图模式
      organizationType: 0,
      //组织结构数据
      orgSource: [],
      //当前选择的租户
      currentTenant: {},
      expandedKeys: [],
      selectedKeys: [],
      autoExpandParent: true,
      currenData: {},
      //项目列表
      projectData: [],
    };
  },
  computed: {
    ...mapGetters(["tenant", "organization", "projectSource"]),
  },
  watch: {
    //当前选择的租户
    tenant: {
      handler(val) {
        this.currentTenant = val;
        let cloneData = _.cloneDeep(val);
        let flatData = flatTreeData([cloneData], "child");
        this.expandedKeys = flatData.map((v) => v.tenantCode);
        //格式化树形数据
        let dealData = addAttributeByKey(
          null,
          "scopedSlots",
          { icon: "custom" },
          [cloneData],
          "child"
        );
        //处理顶层节点
        if (dealData.length > 0) {
          dealData[0].scopedSlots = { icon: "group" };
        }
        this.orgSource = dealData;
      },
      immediate: true,
      deep: true,
    },

    //当前组织结构
    organization: {
      handler(val) {
        let { proCode, tenantCode } = val;
        if (!proCode) {
          this.selectedKeys = [tenantCode];
        }
        this.currenData = val;
      },
      immediate: true,
    },

    //项目列表数据
    projectSource: {
      handler(val) {
        val.forEach((v) => {
          v.tenantName = v.proName;
        });
        this.projectData = val;
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {},
  methods: {
    //打开选择租户弹窗
    openChooseTenant() {
      this.visible = false;
      this.$emit("chooseTenant");
    },

    //选择组织结构
    selectOrganization(_, { selected, node }) {
      let { dataRef } = node;
      this.visible = false;
      saveData("ORGANIZATION", dataRef);
      this.selectedKeys = [dataRef.tenantCode];
      this.queryPermissionData();
    },

    //查询项目列表
    getProjectSource() {
      return new Promise((resolve, reject) => {
        this.$store.dispatch("queryTenantProjectSourceData");
      });
    },

    //选择项目
    selectProject(item = {}) {
      this.selectedKeys = [];
      this.visible = false;
      saveData("ORGANIZATION", item);
      this.queryPermissionData();
    },

    //查询权限菜单数据
    queryPermissionData() {
      this.$store.dispatch("queryPermissionData").then((res) => {
        //数据看板
        let dataBoard = res.find((v) => v.menuType == 2) ?? {};
        saveData("DATA_BOARD", dataBoard);
        //菜单
        saveData("CURRENT_MENU", getMenuData(0));
      });
    },

    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //切换视图模式
    checkOrganizationType(type) {
      this.organizationType = type;
      type == 1 && this.getProjectSource();
    },

    //监听显示&隐藏
    visibleChange(visible) {
      if (visible) {
        let { organization } = this.$store.getters;
        this.organizationType = organization.proCode ? 1 : 0;
      }
    },
    getContainer() {
      return document.getElementById("choose-organization-container");
    },
  },
};
</script>

<style lang="less" scoped>
.choose-organization-container {
  width: 240px;
  height: 100%;
  margin-left: 20px;
  position: relative;
  cursor: pointer;
  &::before,
  &:after {
    height: 24px;
    width: 2px;
    background: rgba(255, 255, 255, 0.4);
    transform: translateY(-50%);
    border-right: 1px solid rgba(0, 0, 0, 0.8);
    content: "";
    position: absolute;
    top: 50%;
  }
  &::before {
    left: 0;
  }
  &::after {
    content: "";
    right: 0;
  }
  .popover-target-container {
    width: 100%;
    height: 100%;
    padding: 0 42px 0 20px;
    cursor: pointer;
    .flex();
    align-items: center;
    justify-content: center;
    font-size: 16px;
    font-family: Microsoft YaHei;
    font-weight: 400;
    color: #ffffff;
    overflow: hidden;
    position: relative;
    .name {
      width: 100%;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      margin-right: 12px;
    }
    .anticon {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      right: 20px;
      font-size: 12px;
      transition: 0.2s;
      &.rotate {
        transform: rotate(-180deg);
        margin-top: -7px;
      }
    }
  }
  /deep/.choose-organization-popover {
    .ant-popover-inner-content {
      padding: 0;
    }
    .popover-drow-container {
      width: 420px;
      height: 450px;
      display: flex;
      flex-direction: column;
      .popover-drow-header {
        height: 58px;
        border-bottom: 1px solid #e8e8e8;
        margin: 0 20px;
        .flex();
        align-items: center;
        flex-shrink: 0;
        .check-button-warp {
          flex-shrink: 0;
          .flex();
          align-items: center;
          justify-content: center;
          .check-button {
            width: 32px;
            height: 32px;
            background: #f1f2f7;
            border-radius: 4px;
            cursor: pointer;
            .flex();
            justify-content: center;
            align-items: center;
            /deep/.bj-icon {
              &::before {
                font-size: 18px;
              }
            }
            &.active {
              background: var(--primary-color);
              color: #fff;
            }
            &:not(:first-child) {
              margin-left: 10px;
            }
            color: var(--primary-color);
          }
        }
        .tenant-name {
          flex: 1;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
          padding: 0 20px;
          font-size: 16px;
        }
      }
      .popover-drow-body {
        flex: 1;
        padding: 10px 0;
        overflow: hidden;
        .carousel-item-container {
          height: 100%;
          padding: 0 20px;
          /deep/.ant-tree {
            .ant-tree-title {
              font-size: 15px;
            }
            .bj-icon-tree_line {
              margin-right: 4px;
              &::before {
                font-size: 18px !important;
              }
            }
            .bj-icon-project_space {
              margin-right: 4px;
              &::before {
                font-size: 18px !important;
              }
            }
            .ant-tree-treenode-selected {
              .bj-icon-project_space {
                margin-right: 4px;
                &::before {
                  font-size: 18px !important;
                }
              }
            }
          }

          .pro-list-warp {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            cursor: pointer;
            padding: 8px 20px;
            &:hover {
              background-color: #e5f6ff;
            }
            &.active {
              background: var(--primary-color);
              color: #fff;
            }
          }
        }
        /deep/.ant-carousel {
          .slick-dots {
            height: 32px;
            top: -55px;
            right: 0;
            width: auto;
            display: none !important;
          }
        }
      }
    }
  }
}
</style>
